package com.sptpc.stu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.sptpc.stu.common.response.JSONResponse;
import com.sptpc.stu.controller.request.AddNewUserRequest;
import com.sptpc.stu.controller.request.NewAccountRequest;
import com.sptpc.stu.controller.request.SearchaAccRequest;
import com.sptpc.stu.model.my.Register;
import com.sptpc.stu.model.my.User;
import com.sptpc.stu.repository.my.RegisterRepository;
import com.sptpc.stu.repository.my.UserRepository;
import com.sptpc.stu.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.Optional;
import java.util.Random;

import static cn.hutool.crypto.digest.DigestUtil.md5;


@Component
public class RegisterServiceImpl implements MailService {
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RegisterRepository registerRepository;

    private String randomInteger() {
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        //生成6位的随机数
        for (int i = 0; i < 6; i++) {
            int i1 = random.nextInt(10);
            stringBuffer.append(i1);
        }
        return stringBuffer.toString();
    }

    @Override
    public JSONResponse sendCodeMail(String email, HttpSession session) {
        if (userRepository.existsByEmail(email))
        {
            return JSONResponse.ofFail("邮箱已存在");
        }
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();

            mailMessage.setSubject("验证码邮件");//主题
            //生成随机数
            String code = randomInteger();

            //将随机数放置到session中
            session.setAttribute("email",email);
            session.setAttribute("code",code);

            mailMessage.setText("您收到的验证码是："+code);//内容

            mailMessage.setTo(email);//发给谁

            mailMessage.setFrom(from);//你自己的邮箱

            javaMailSender.send(mailMessage);//发送

            String sessionId = session.getId();

            if (registerRepository.existsBySessionId(sessionId))
            {
                Register re = registerRepository.findRegisterBySessionId(sessionId);

                re.setCode(code);

                registerRepository.saveAndFlush(re);

                return  JSONResponse.ofMessage(sessionId);

            }
            registerRepository.save(new Register(sessionId,code));

            return JSONResponse.ofMessage(sessionId);

        }catch (Exception e){

            e.printStackTrace();
        }
        return JSONResponse.ofFail("发送失败");
    }


    @Override
    public JSONResponse registeredOrUpdate(AddNewUserRequest newAccountRequest) {

        if(!userRepository.existsByEmail(newAccountRequest.getEmail())) {

                    newAccountRequest.setPassword(DigestUtil.md5Hex(newAccountRequest.getPassword()));

                    User user = new User();

                    if(newAccountRequest.getAvatar()!=null) {

                        newAccountRequest.setAvatar(newAccountRequest.getAvatar().substring("https://localhost".length()));
                    }

                    BeanUtil.copyProperties(newAccountRequest,user);
                    //将数据写入数据库
                    userRepository.save(user);

                    registerRepository.delete(registerRepository.findRegisterBySessionId(newAccountRequest.getSessionId()));

                    //跳转成功页面
                    return JSONResponse.ofSuccess();

            } else {
            return JSONResponse.ofFail("注册邮箱已存在");
        }

    }

    @Override
    public JSONResponse loginIn(SearchaAccRequest newAccountRequest) {

        if (userRepository.existsByAccountPhone(newAccountRequest.getAccountPhone())||userRepository.existsByEmail(newAccountRequest.getEmail()))
        {
            Optional<User> findAccount =
                    userRepository.findByAccountPhoneOrEmail(newAccountRequest.getAccountPhone(),newAccountRequest.getEmail());

            if (DigestUtil.md5Hex(newAccountRequest.getPassword()).equals(findAccount.get().getPassword()))
            {
                return JSONResponse.ofSuccess(findAccount);

            } else {

                return JSONResponse.ofFail("密码或账号错误");
            }

        }else{

            return JSONResponse.ofFail("账号不存在");
        }

    }

    @Override
    public JSONResponse checkCode(AddNewUserRequest newUserRequest) {

        String ecode = registerRepository.findRegisterBySessionId(newUserRequest.getSessionId()).getCode();

        if (newUserRequest.getEcode().equals(ecode))
        {
            registerRepository.existsBySessionId(newUserRequest.getSessionId());
            return JSONResponse.ofSuccess();
        }else {
            return JSONResponse.ofFail("验证码不正确");
        }
    }

}


